<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>STOMP</title>
</head>
<body onload="disconnect()">
<h1 id="tip">消息发布订阅测试页</h1>
请输入token:<input type="text" id="token" placeholder=""> <br>
<button onclick="connect()" id="connect">connect</button>
<button onclick="disconnect()" id="disconnect">disconnect</button>

<p>输入消息: <span id="msg"></span></p>
<input type="text" id="content" placeholder=""> <br>
<button onclick="send()">send</button>

<ul id="ul">
    回答消息<p id="answer"></p>
    单播消息<p id="single"></p>
    广播消息<p id="board"></p>
</ul>
<script src="sockjs.min.js"></script>
<script src="stomp.min.js"></script>
<script>
    var stompClient = null;
    var endpoint = "/ws";

    //断开连接
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnect(false);
        console.log("disconnected");
    }
    //建立连接
    function connect() {
        var token = document.getElementById("token").value;
        if (token === '' || token === undefined) {
            alert("请输入token");
            return;
        }
        //连接请求头里面，设置好我们提前获取好的token
        var headers = {
            token: token
        };
        var url = endpoint;
        var socket = new SockJS(url);
        stompClient = Stomp.over(socket);
        //建立连接
        stompClient.connect(headers, function (msg) {
            setConnect(true);
            console.log("connected:" + msg);
            //订阅了三个topic
            //订阅用户消息topic1
            stompClient.subscribe("/user/topic/answer", function (response) {
                createElement("answer", response.body);
            });
            //订阅用户消息topic2
            stompClient.subscribe("/user/topic/single/hello", function (response) {
                createElement("single", response.body);
            });
            //订阅广播消息topic
            stompClient.subscribe("/topic/boardCast/hello", function (response) {
                createElement("board", response.body);
            });
        });
    }
    //主动发送消息给服务器，对应的后端topic为/app/echo
    function send() {
        var value = document.getElementById("content").value;
        var msg = {
            msgType: 1,
            content: value
        };
        stompClient.send("/app/echo", {}, JSON.stringify(msg));
        //stompClient.send("/app/echo2", {}, JSON.stringify(msg));
    }

    function createElement(eleId, msg) {
        var singleP = document.getElementById(eleId);
        var p = document.createElement("p");
        p.style.wordWrap = "break-word";
        p.appendChild(document.createTextNode(msg));
        singleP.appendChild(p);
    }

    function setConnect(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
    }
</script>
</body>
</html>